﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Psm.Session;
using Psm.Messaging;
using Psm.PubSub.Messaging;
using Psm.PubSub.StateCache;
using Psm.PubSub.Configuration;
using Psm.Logging;
using Psm.Container;
using System.Threading;
using System.Diagnostics;

namespace Psm.PubSub.Processors
{
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Export("CACHE_PROCESSOR_PUBLICATION", typeof(IProcessor))]
    public class CachePublicationProcessor : IProcessor
    {
        private static ILogger logger = Repository.GetInstance<ILogger>();
        private Dictionary<string, Dictionary<string, int>> topicKeyHash = new Dictionary<string, Dictionary<string, int>>();
        Stopwatch watch = new Stopwatch();

        public void  ProcessMessage(ISession session, IMessage incoming)
        {
            DataMessageInternal message = incoming as DataMessageInternal;
            if (message != null)
            {
                TopicSpace space = StateCache.StateCache.Instance.GetTopicSpace(message.Topic);
                if (space != null)
                {
                    string messageKey = message.Key;
                    Dictionary<string, int> keyHash = topicKeyHash[space.Name];
                    if (messageKey != null)
                    {
                        if (keyHash.ContainsKey(messageKey))
                        {
                            space.UpdateMessage(message, keyHash[messageKey]);
                        }
                        else
                        {
                            int index = space.AddMessage(message);
                            keyHash[messageKey] = index;
                        }
                    }
                }
            }
        }

        public void Intialize()
        {
            foreach (TopicSpace space in StateCache.StateCache.Instance.GetAllSpaces())
                this.topicKeyHash.Add(space.Name, new Dictionary<string, int>());
        }

        public void NewSession(ISession session)
        {
            foreach (Schema schema in SchemaCollection.AllSchemas.Values)
            {
                session.SendMessage(new SchemaMessage(schema));
            }
            session.SendMessage(new SchemaMessage((Schema)null));
            session.Flush();
        }

        public void SessionClosed(ISession session)
        {
           
        }
    }
}
